﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBlog.IService;
using MyBlog.Model;
using MyBlog.Service;
using MyBlog.WebApi.Utility;

namespace MyBlog.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TypeController : ControllerBase
    {
        private readonly ITypeInfoService _iTypeInfoService;

        public TypeController(ITypeInfoService typeInfoService)
        {
            _iTypeInfoService = typeInfoService;
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("Types")]
        public async Task<ApiResult> Types()
        {
            var types = await _iTypeInfoService.QueryAsync();
            if (types.Count == 0)
                return ApiResultHelper.Error("没有查询到数据");
            return ApiResultHelper.Success(types);
        }


        /// <summary>
        /// 创建类型
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost("Create")]
        public async Task<ApiResult> Create(string name)
        {
            if (string.IsNullOrEmpty(name))
                return ApiResultHelper.Error("类型不能为空");
            TypeInfo type = new TypeInfo
            {
                Name = name
            };
            bool b = await _iTypeInfoService.CreateAsync(type);
            if (!b)
                return ApiResultHelper.Error("添加失败");
            return ApiResultHelper.Success(b);
        }

        /// <summary>
        /// 编辑类型
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPut("Edit")]
        public async Task<ApiResult> Edit(int id, string name)
        {
            var type = await _iTypeInfoService.FindAsync(id);
            if (type == null)
                return ApiResultHelper.Error("没有找到文章类型数据");
            type.Name = name;
            bool b = await _iTypeInfoService.EditAsync(type);
            if (!b)
                return ApiResultHelper.Error("修改失败");
            return ApiResultHelper.Success(type);
        }

        /// <summary>
        /// 删除类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("Delete")]
        public async Task<ApiResult> Delete(int id)
        {
            bool b = await _iTypeInfoService.DeleteAsync(id);
            if (!b)
                return ApiResultHelper.Error("删除失败");
            return ApiResultHelper.Success(b);
        }

    }
}
